import Toast from 'tdesign-miniprogram/toast/index';
import {
  domain
} from '../../../utils/request'
import {
  putPerson,
  getPerson
} from '@/services/usercenter/fetchPerson'

Page({
  data: {
    personInfo: {
      avatarUrl: '',
      nickName: '',
      gender: 0,
      phoneNumber: '',
    },
    showUnbindConfirm: false,
    pickerOptions: [{
        name: '男',
        code: '1',
      },
      {
        name: '女',
        code: '2',
      },
    ],
    typeVisible: false,
    genderMap: ['', '男', '女'],
  },
  onLoad() {
    this.init();
  },
  async onShow() {
    let userInfo = wx.getStorageSync('userInfo')
    userInfo = await getPerson({
      id: userInfo.id
    });
    this.setData({
      personInfo: userInfo
    })
    wx.setStorageSync('userInfo', userInfo)
  },
  init() {
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      personInfo: userInfo
    })
  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;

    console.log(dataset)
    switch (dataset.type) {
      case 'gender':
        this.setData({
          typeVisible: true,
        });
        break;
      case 'text':
        wx.navigateTo({
          url: `/pages/usercenter/name-edit/index?text=${dataset.content}&label=${dataset.label}&key=${dataset.key}`,
        });
        break;
      case 'avatarUrl':
        this.toModifyAvatar();
        break;
      default: {
        break;
      }
    }
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
        typeVisible: false,
        'personInfo.gender': value,
      },
      () => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '设置成功',
          theme: 'success',
        });
      },
    );
  },
  async toModifyAvatar() {
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseMedia({
          count: 1,
          mediaType: ['image'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            console.log(res)
            const {
              tempFilePath,

            } = res.tempFiles[0];
            resolve(tempFilePath);
          },
          fail: (err) => reject(err),
        });
      });

      wx.uploadFile({
        url: `${domain}/upload`,
        filePath: tempFilePath,
        name: 'file',
        formData: {
          file: tempFilePath
        },
        success: async res => {
          const imgUrl = `${JSON.parse(res.data).data.imgUrl}`
          this.setData({
            ['personInfo.imgUrl']: imgUrl
          })
          await putPerson({
            imgUrl,
            id: this.data.personInfo.id
          })
        },
      })
    } catch (error) {
      console.log(error)
      if (error.errMsg === 'chooseImage:fail cancel') return;
    }
  },
});